﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using ExpressionEvaluator.BuilderTreeNode;

namespace ExpressionEvaluator.Extended
{
	internal class ParameterForLambdaResolve
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="ParameterForLambdaResolve"/> class.
		/// </summary>
		/// <param name="nonLambdaParamExpression">The non lambda param expression.</param>
		public ParameterForLambdaResolve(Expression nonLambdaParamExpression)
		{
			IsLambda = false;
			NonLambdaParamExpression = nonLambdaParamExpression;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="ParameterForLambdaResolve"/> class.
		/// </summary>
		/// <param name="lambdaNode">The lambda node.</param>
		public ParameterForLambdaResolve(BuilderTreeNodeBase lambdaNode)
		{
			IsLambda = true;
			LambdaNode = lambdaNode;
			// precompute lambda parameters
			LambdaParameters = GetLambdaParameterNames(lambdaNode);
		}


		/// <summary>
		/// Gets or sets a value indicating whether this instance is lambda.
		/// </summary>
		/// <value><c>true</c> if this instance is lambda; otherwise, <c>false</c>.</value>
		public bool IsLambda
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets or sets the lambda node.
		/// </summary>
		/// <value>The lambda node.</value>
		public BuilderTreeNodeBase LambdaNode
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets or sets the lambda parameters.
		/// </summary>
		/// <value>The lambda parameters.</value>
		public string[] LambdaParameters
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets or sets the non lambda param expression.
		/// </summary>
		/// <value>The non lambda param expression.</value>
		public Expression NonLambdaParamExpression
		{
			get;
			private set;
		}


		/// <summary>
		/// Gets the lambda parameter names.
		/// </summary>
		/// <param name="lambdaNode">The lambda node.</param>
		/// <returns>List of lambda parameter names.</returns>
		private static string[] GetLambdaParameterNames(BuilderTreeNodeBase lambdaNode)
		{
			List<string> result = new List<string>();
			if (lambdaNode.Nodes.Count > 0)
			{
				// if bracket node, get multiple params
				if (lambdaNode.Nodes[0] is BracketNode)
				{
					foreach (var node in lambdaNode.Nodes[0].Nodes)
					{
						result.Add(node.ToString());
					}
				}
				else
				{
					result.Add(lambdaNode.Nodes[0].ToString());
				}
			}
			return result.ToArray();
		}
	}
}
